var fs = require('fs');
var workPath = fs.dirname(fs.absolute(phantom.casperScript));
var util = require(workPath + fs.separator + '../util');
var cfg = util.getDefaultCfg();
cfg.clientScripts = ['bdnovel.js'];

var onError = function(msg, trace) {
    var msgStack = ['ERROR: ' + msg];

    if (trace && trace.length) {
        msgStack.push('TRACE:');
        trace.forEach(function(t) {
            msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function+'")' : ''));
        });
    }

    casper.echo('ERROR==>' + msgStack.join('\n'), 'ERROR');
}

var casper = util.getCasper(cfg);

casper.on('page.error', onError);

var url = 'http://m.baidu.com/tc?appui=alaxs&gid=1768429347&srd=1&src=http%3A%2F%2Fwww.qingxinwang.com%2Ffiles%2Farticle%2Fhtml%2F16%2F16830';
var filename = 'gzjdnr.data.json';
var args = casper.cli.args;
if (args.length == 2) {
    url = args[0];
    filename = args[1];
}else if(args.length==1){
    filename = args[0];
}

casper.url = url;
casper.filename = filename;



function start(targetUrl) {
    this.start(targetUrl, function() {
        var rtn = this.evaluate(function() {
            app.injectExtension.getAllChapter();
            __utils__.echo('execute the getAllChapter');
            return true;
        });
        this.echo('execute return:' + rtn, 'DEBUG');
        if (rtn) {
            casper.isRunning = true;
        }
    });
}

casper.start(url);

function check() {
    if (!casper.isRunning) {
        start.call(this, casper.url);
    } else {
        this.wait(3000, function() {
            this.echo("I'm waiting for processing...", 'INFO');
        });
    }
    var isDone = this.evaluate(function() {
        return app.injectExtension.checkAllDone();
    });
    this.echo('isDone? ' + isDone);
    if (!isDone) {
        var percent = this.evaluate(util.wrapEvaluate(function() {
            var ext = app.injectExtension;
            var chapterGroup = ext.chapterGroup;
            var chapterContents = ext.chapterContents;
            return chapterGroup?chapterContents.length / chapterGroup.length:0;
        }));
        this.echo('complete pecent is ' + parseInt((percent * 100)) + '%');
        this.run(check);
    } else {
        var chapterContents = this.evaluate(util.wrapEvaluate(function() {
            var ext = app.injectExtension;
            return ext.chapterContents;
        }));
        fs.write(casper.filename, JSON.stringify(chapterContents), 'w');
        this.echo('Done');
        this.exit();
    }
}

casper.run(check);
